// src/composables/useMqtt.ts
import { ref, onUnmounted } from "vue";
import mqtt from "mqtt";

export function useMqtt(clientId: string, username: string, password: string) {
  console.log(clientId);
  console.log(username);
  console.log(password);

  const client = mqtt.connect("ws://mqtt.jz-iot.cn:8083/mqtt", {
    connectTimeout: 4000,
    clientId,
    username,
    password,
  });

  client.on("connect", () => {
    console.log("MQTT 客户端连接成功");
  });

  client.on("error", (error) => {
    console.error("MQTT 连接出错:", error);
  });

  client.on("close", () => {
    console.log("MQTT 连接已关闭");
  });

  client.on("reconnect", () => {
    console.log("MQTT 正在重连...");
  });

  // 动态订阅主题
  const subscribe = (topic: string) => {
    client.subscribe(topic, (err) => {
      if (err) {
        console.error(`订阅主题失败: ${topic}`, err);
      } else {
        console.log(`成功订阅主题: ${topic}`);
      }
    });
  };

  // 清理
  onUnmounted(() => {
    client.end();
    console.log("手动关闭MQTT 客户端");
  });

  return {
    client,
    subscribe,
  };
}
